<template>
    <!-- <div class="parent">
        <div ref="konva-container" id="konva-container"></div>
    </div> -->

    <div class="main-container">
        <div v-if="uploadLoading" class="fullscreen-loading">
            <div class="loading-content">
                <div class="spinner"></div>
                <p>文件解析中，请稍候...</p>
            </div>
        </div>

        <div class="button-container">
            <el-button @click="goBack" class="back-button" icon="ArrowLeftBold"></el-button>
        </div>
        <div class="main-card">
            <div class="card-container">
                <div class="left-card">
                    <div class="chat-list">
                        <el-scrollbar ref="scrollbarRef" >
                            <div v-for="(message, index) in messages" :key="index" class="message-container" :class="{'remote-message': !message.isLocal, 'local-message': message.isLocal}">
                                <div class="avatar">
                                    <img v-if="message.isLocal" src="/assets/local.png" alt="Avatar" />
                                    <img v-else src="/assets/remote.png" alt="Avatar" />
                                </div>
                                <div class="bubble" v-html="renderMath(preprocessContent(message.text))">
                                </div>
                            </div>
                        </el-scrollbar>
                    </div>
                    <div class="input-area">
                        <div class="input-tools">
                            <el-button icon="Document" circle @click="triggerFileUpload"></el-button>
                            <el-button icon="VideoPause" circle @click="stopAnswer"></el-button>
                            <el-button icon="Microphone" circle @click="toggleMicrophone" :style="microphoneStyle"></el-button>
                            <el-button icon="VideoCamera" circle @click="toggleCamera" :style="videoStyle"></el-button>
                            <el-button icon="Phone" circle @click="hangupTalk" :style="hangupStyle"></el-button>
                        </div>
                        <el-input
                            class="input-message"
                            v-model="inputMessage"
                            type="textarea"
                            :autosize="{ minRows: 4, maxRows: 6 }"
                            placeholder="请输入消息"
                            @keydown="handleKeydown"
                        >
                            <template #append>
                                <el-button @click="sendMessage">发送</el-button>
                            </template>
                        </el-input>
                    </div>
                </div>
                <div class="right-card">
                    <div class="text-display" id="konva-container"  ref="konvacontainer">
                    </div>
                    <div class="pagger" v-if="pdfloadsuccess">
                        <el-button @click="goPrePage" icon="ArrowLeftBold"></el-button>
                        <el-button @click="goNextPage" icon="ArrowRightBold"></el-button>
                    </div>
                    <div class="button-bar">
                        
                        <el-button class="opt-button" circle @click="drawTypeFunc(1)">
                            <template #icon>
                                <img v-if="currentDrawType === 0" src="/assets/draw1on.png" alt="Custom Icon" class="custom-icon" />
                                <img v-else src="/assets/draw1.png" alt="Default Icon" class="custom-icon" />
                            </template>
                        </el-button>
                        <el-button class="opt-button" circle @click="drawTypeFunc(2)">
                            <template #icon>
                                <img v-if="currentDrawType === 1" src="/assets/draw2on.png" alt="Custom Icon" class="custom-icon" />
                                <img v-else src="/assets/draw2.png" alt="Default Icon" class="custom-icon" />
                            </template>
                        </el-button>
                        <el-button class="opt-button" circle @click="drawTypeFunc(3)">
                            <template #icon>
                                <img v-if="currentDrawType === 2" src="/assets/draw3on.png" alt="Custom Icon" class="custom-icon" />
                                <img v-else src="/assets/draw3.png" alt="Default Icon" class="custom-icon" />
                            </template>
                        </el-button>
                        <el-button class="opt-button" circle  @click="drawTypeFunc(4)">
                            <template #icon>
                                <img v-if="currentDrawType === 3" src="/assets/draw4on.png" alt="Custom Icon" class="custom-icon" />
                                <img v-else src="/assets/draw4.png" alt="Default Icon" class="custom-icon" />
                            </template>
                        </el-button>
                        <el-button class="opt-button" circle @click="drawTypeFunc(5)">
                            <template #icon>
                                <img v-if="currentDrawType === 4" src="/assets/draw5on.png" alt="Custom Icon" class="custom-icon" />
                                <img v-else src="/assets/draw5.png" alt="Default Icon" class="custom-icon" />
                            </template>
                        </el-button>
                        <!-- <el-button class="opt-button" circle @click="drawTypeFunc(7)">
                            <template #icon>
                                <img src="/assets/draw3.png" alt="Custom Icon" class="custom-icon" />
                            </template>
                        </el-button> -->
                        <el-button class="opt-button" circle @click="drawTypeFunc(6)">
                            <template #icon>
                                <img src="/assets/draw6.png" alt="Custom Icon" class="custom-icon" />
                            </template>
                        </el-button>
                    </div>
                </div>
            </div>
        </div>
        <input type="file" ref="fileInput" @change="handleFileChange" style="display: none;">
    </div>

  </template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { Stage, Layer, Circle, Rect, Text,Line } from 'konva';

const konvacontainer = ref(null);
const stage = ref(null);
const layer = ref(null);
const isDrawing = ref(false);
const currentLine = ref(null);
const lines = ref([]);

//记录历史操作
const historyStack = ref([]);
const currentStep = ref(-1);

// 初始化舞台并设置尺寸
const initStage = () => {
  if (!konvacontainer.value) return;
  
  const width = konvacontainer.value.clientWidth;
  const height = konvacontainer.value.clientHeight;

  stage.value = new Stage({
    container: konvacontainer.value,
    width: width,
    height: height,
  });

  layer.value = new Layer();
  stage.value.add(layer.value);

// // 添加一个圆形
// const circle = new Circle({
//     x: 100,
//     y: 100,
//     radius: 50,
//     fill: 'red',
//     stroke: 'black',
//     strokeWidth: 2,
//   });
//   layer.value.add(circle);

//   // 添加一个矩形
//   const rect = new Rect({
//     x: 200,
//     y: 200,
//     width: 100,
//     height: 100,
//     fill: 'green',
//     draggable: true, // 允许拖拽
//   });
//   layer.value.add(rect);

//   // 添加文本
//   const text = new Text({
//     x: 50,
//     y: 300,
//     text: 'Vue3 + Konva.js',
//     fontSize: 20,
//     fontFamily: 'Arial',
//     fill: 'blue',
//   });
//   layer.value.add(text);
//   layer.value.draw();
  setOptions();

  saveState();
};

const setOptions = ()=>{
  stage.value.on('mousedown touchstart', () => {
    isDrawing.value = true;
    const pos = stage.value.getPointerPosition();
    currentLine.value = new Line({
      points: [pos.x, pos.y],
      stroke: 'black',
      strokeWidth: 3,
    });
    layer.value.add(currentLine.value);
    layer.value.draw();
  });

  stage.value.on('mousemove touchmove', () => {
    if (!isDrawing.value || !currentLine.value) return;
    const pos = stage.value.getPointerPosition();
    currentLine.value.points(currentLine.value.points().concat([pos.x, pos.y]));
    layer.value.batchDraw();
  });

  stage.value.on('mouseup touchend', () => {
    if (!currentLine.value) return;
    isDrawing.value = false;
    lines.value.push(currentLine.value.attrs);
    currentLine.value = null;
    saveState();
  });
}

const drawTypeFunc = (type)=>{
    console.log("type",type);
    switch(type){
        case 5:
            undo();
            break;
    }
};

// 撤销上一步
const undo = () => {
    console.log("undo",currentStep.value);
  if (currentStep.value <= 0) return; // 已到初始状态

  currentStep.value--;
  loadState(historyStack.value[currentStep.value]);
};

// 从历史状态恢复舞台
const loadState = (state) => {
  // 清空当前舞台
  layer.value.destroyChildren();
  stage.value.clear();

  // 反序列化历史状态
  const newStage = Konva.Node.create(state, 'konvacontainer');
  stage.value = newStage;
  layer.value = stage.value.getLayers()[0]; // 重新获取图层引用
  setOptions();
};

// 保存舞台状态到历史栈
const saveState = () => {
  // 移除当前指针之后的所有状态（避免分支）
  if (currentStep.value < historyStack.value.length - 1) {
    historyStack.value = historyStack.value.slice(0, currentStep.value + 1);
  }

  // 序列化当前舞台状态（关键！）
  const state = stage.value.toObject({
    includeChildren: true, // 包含所有子节点
  });

  historyStack.value.push(state);
  currentStep.value = historyStack.value.length - 1;

  // 限制历史深度（例如最多20步）
  if (historyStack.value.length > 20) {
    historyStack.value.shift();
    currentStep.value--;
  }
};

// 监听窗口大小变化
const handleResize = () => {
  if (!stage.value || !konvacontainer.value) return;
  stage.value.width(konvacontainer.value.clientWidth);
  stage.value.height(konvacontainer.value.clientHeight);
  stage.value.draw(); // 重绘舞台
};

onMounted(() => {
  initStage();
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  stage.value?.destroy(); // 销毁舞台
});
</script>

<style>
.main-container {
    width: 100vw;
    height: 100vh;
    background: linear-gradient(to bottom right, #D6E8FD, #B7D4FC);
    overflow: hidden; /* 防止出现滚动条 */
    display: flex;
    flex-direction: column;
}

.button-container {
    margin: 10px 0px 10px 20px; /* 添加内边距以避免按钮紧贴边缘 */
}

.back-button {
    width: 50px; /* 设置按钮的宽度 */
    height: 50px; /* 设置按钮的高度 */
    padding: 0; /* 移除默认的内边距 */
    border-radius: 50%; /* 使按钮变成圆形 */
    display: flex; /* 使用 flex 布局 */
    align-items: center; /* 垂直居中 */
    justify-content: center; /* 水平居中 */
}

.main-card {
    flex-grow: 1; /* 占据剩余的所有高度 */
    border-radius: 13px;
    margin: 00px 20px 20px 20px; /* 调整边距以避免重叠 */
    background: rgba(255, 255, 255, 0.21);
    border: 1px solid #FFFFFF;
    box-sizing: border-box; /* 确保边框和内边距包含在宽度和高度内 */
    display: flex; /* 使用 flex 布局 */
    flex-direction: column; /* 垂直排列子元素 */
    padding: 10px 20px 10px 10px; /* 添加内边距以避免子卡片紧贴边缘 */
    height: 100%;
}

.card-container {
    display: flex; /* 使用 flex 布局 */
    gap: 10px; /* 设置子卡片之间的间距 */
    flex-grow: 1; /* 占据 main-card 的全部高度 */
    height: 100%;
}

.left-card {
    flex: 0 0 60%; /* 左侧卡片占 60% 宽度 */
    height: 100%;
    background: linear-gradient( 139deg, #E2EEFE 0%, #E2EBF7 12%, #E2F2FC 63%, #E1EEFF 100%);
    box-shadow: 0px 2px 10px 1px rgba(127,183,231,0.26);
    border-radius: 13px 13px 13px 13px;
    border: 1px solid rgba(255,255,255,0.27);
    padding: 20px; /* 添加内边距 */
    box-sizing: border-box; /* 确保边框和内边距包含在宽度和高度内 */
    display: flex;
    flex-direction: column;
    position: relative;
}

.chat-list {
    flex-grow: 1;
    margin-bottom: 10px;
    height: 400px;
    /* height: calc(100% - 150px); */
    /* height: 500px; */
}

.message-container {
    display: flex;
    align-items: flex-start;
    margin-bottom: 10px;
}

.remote-message {
    flex-direction: row;
}

.local-message {
    flex-direction: row-reverse;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
    margin-left: 10px;
}

.avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.bubble {
    max-width: 70%;
    padding: 10px;
    border-radius: 15px;
    background-color: #f0f2f5;
    box-shadow: 0px 2px 3px rgba(0, 0, 0, 0.1);
    white-space: pre-wrap; 
}

.local-message .bubble {
    background-color: #4496FB;
    color: white;
}
.input-area {
    position: relative;
    width: 100%;
    display: flex;
    flex-direction: column;
    background: #F7F9FF;
    box-shadow: 0px 2px 3px 1px rgba(44,133,238,0.37);
    border-radius: 13px 13px 13px 13px;
    border: 1px solid #4496FB;
    padding: 5px;
    box-sizing: border-box;
}

.input-tools {
    position: absolute;
    right: 20px;
    gap: 10px;
    bottom: 20px;
    z-index: 1;
}

.input-tools .el-button {
    background-color: #f0f2f5;
    border-color: #dcdfe6;
    color: #606266;
}

.input-tools .el-button:hover {
    background-color: #e4e7ed;
    border-color: #c4c9d1;
    color: #409EFF;
}


.right-card {
    flex: 0 0 40%; /* 右侧卡片占 40% 宽度 */
    height: 100%;
    background: #FFFFFF;
    border-radius: 16px 16px 16px 16px;
    border: 1px solid rgba(139,186,184,0.41);
    box-sizing: border-box; /* 确保边框和内边距包含在宽度和高度内 */
    position: relative; /* 设置相对定位以便子元素绝对定位 */
    display: flex;
    flex-direction: column;
}

.text-display {
    flex-grow: 1; /* 占据剩余的所有高度 */
    height: 80vh;
    overflow-y: auto; /* 添加垂直滚动条 */
}

.button-bar {
    position: absolute; /* 绝对定位 */
    bottom: 0; /* 紧贴底部 */
    left: 0;
    right: 0;
    height: 80px; /* 设置高度 */
    background: #CFEAFF;
    /* border-top: 1px solid #4496FB; */
    border-radius: 0px 0px 16px 16px;
    display: flex;
    justify-content: space-around; /* 横向居中并分散排列 */
    align-items: center; /* 垂直居中 */
}

.pagger {
    position: absolute; /* 绝对定位 */
    bottom: 100px; /* 紧贴底部 */
    left: 0;
    right: 0;
    height: 50px; /* 设置高度 */
    background: transparent;
    display: flex;
    justify-content: space-between; /* 横向居中并分散排列 */
    align-items: center; /* 垂直居中 */
}

.opt-button {
    height:45px;
    width:45px !important;
    font-size: 20px;
    background-color: transparent;
    border: transparent;
}

.video-layer{
    position: absolute; /* 绝对定位 */
    bottom: 0; /* 紧贴底部 */
    left: 0; /* 紧贴左侧 */
    width: 80px; /* 设置宽度 */
    height: 142px; /* 设置高度 */
    background-color: #4496FB; /* 背景颜色 */
    border-radius: 8px; /* 圆角 */
    z-index: 1000;
}


.local-player {
    position: absolute; /* 绝对定位 */
    top: 40px; /* 距离顶部 0 */
    right: 40px; /* 距离左侧 0 */
    width: 181px;
    height: 324px; 
    background-color: rgba(255, 255, 255, 0.5); /* 半透明背景 */
    border-radius: 8px;
    z-index: 1000; /* 确保在最上层 */
    border: 1px solid #ccc; /* 边框 */  
    cursor: move; 
}

.question-content {
  font-size: 18px;
  line-height: 1.6;
  margin-bottom: 15px;
}


.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(128, 128, 128, 0.5); /* 灰色半透明背景 */
  display: flex;
  justify-content: center;
  align-items: center;
}

.loading-box {
  background-color: white;
  padding: 20px 30px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

.loading-text {
  color: #333;
  font-size: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}


.fullscreen-loading {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-content {
  background: white;
  padding: 30px;
  border-radius: 8px;
  text-align: center;
}
</style>